package br.com.remedioCerto.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import br.com.remedioCerto.model.Remedio;

public class RemedioDao extends BasicoDao<Remedio> {

	public static final String REMEDIO_TB = "REMEDIO";
	 
	public static final String REMEDIO_COLUNA_ID = "id";
	public static final String REMEDIO_COLUNA_NOME = "NOME";
	public static final String REMEDIO_COLUNA_FOTO = "FOTO";
	
	public static final String REMEDIO_CREATE_TABLE = "CREATE TABLE "	
						+ REMEDIO_TB 			+ "  (" 
						+ REMEDIO_COLUNA_ID 	+ " INTEGER PRIMARY KEY AUTOINCREMENT, " 
						+ REMEDIO_COLUNA_NOME 	+ " TEXT NOT NULL," 
						+ REMEDIO_COLUNA_FOTO 	+ " BLOB NOT NULL);";
	
	public RemedioDao(Context context) {
		super(context);
	}

	@Override
	protected ContentValues toContent(Remedio r) {
		ContentValues cv = new ContentValues();
		cv.put(REMEDIO_COLUNA_NOME, r.getNome());
		cv.put(REMEDIO_COLUNA_FOTO, r.getFoto());
		return cv;
	}

	@Override
	protected Remedio fromCursor(Cursor c) {
		if (c == null || c.getCount() < 1) {
			return null;
		}
	
		Remedio r = new Remedio();
		r.setId(c.getLong(c.getColumnIndex(REMEDIO_COLUNA_ID)));
		r.setNome(c.getString(c.getColumnIndex(REMEDIO_COLUNA_NOME)));
		r.setFoto(c.getBlob(c.getColumnIndex(REMEDIO_COLUNA_FOTO)));
		return r;
	}


	public Remedio findById(Long remedioId){
		Cursor c = consultaBasica(REMEDIO_TB ,null, REMEDIO_COLUNA_ID +" = "+remedioId , null);
		return fromCursor(c);
	}
	
	
	public void adiciona(Remedio remedio){
		
		Long id = inserir(REMEDIO_TB, toContent(remedio));
		if(id!= null && id > 0)remedio.setId(id);
		
	}
	
	public void atualiza(Remedio remedio){
		
		atualizar(REMEDIO_TB, toContent(remedio), REMEDIO_COLUNA_ID,remedio.getId());
	}

	public void remove(Long id){
		remover(REMEDIO_TB, REMEDIO_COLUNA_ID, id);
	}


	public Cursor lista(){
		return consultarTodos(REMEDIO_TB);
	}
	
	public List<Remedio> listaList() {
		List<Remedio> listaRemedio = new ArrayList<Remedio>();
		Cursor c = lista();
	
		while (!c.isAfterLast()) {
			Remedio r = fromCursor(c);
			listaRemedio.add(r);
			c.moveToNext();
		}
		c.close();

		return listaRemedio;
	}
	
}
